package com.foreveross.action.weixin;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.foreveross.SYWebService.vo.ConditionVo;
import com.foreveross.SYWebService.vo.DataVo;
import com.foreveross.action.BaseCostroller;
import com.foreveross.action.SysExpressController;
import com.foreveross.common.CommonUtil;
import com.foreveross.common.Exception.SYHttpclientCallException;
import com.foreveross.service.DDManagerService;
import com.foreveross.service.HouseUserService;
import com.foreveross.service.HrHouseInfoService;
import com.foreveross.util.CheckSumBuilder;
import com.foreveross.util.HttpUtil;
import com.foreveross.util.JSONUtil;
import com.foreveross.util.VlidateDataTools;
import com.foreveross.vo.HouseUser;
import com.foreveross.vo.HrHouses;
import com.foreveross.vo.common.FileVo;
import com.foreveross.vo.common.PageVo;
import com.foreveross.vo.common.ResultVo;

import net.sf.json.JSONArray;

@Controller
@RequestMapping(value = "/weixin/userCenterController")
public class UserCenterController extends BaseCostroller {

	private Logger log = Logger.getLogger(SysExpressController.class);

	@Resource
	private DDManagerService ddManagerService;

	@Resource
	private HrHouseInfoService hrHouseInfoService;

	@Resource
	private HouseUserService houseUserService;
	
	/**
	 * 获取用户基础字典
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/getCodeList")
	public void getCodeList(HttpServletRequest request,
			HttpServletResponse response, String type, String typeName,String houseId) {
		ResultVo resultVo = new ResultVo();
		try {
			Map<String, Object> map = ddManagerService.getCodeList(type, typeName,houseId);
			if(Integer.parseInt(map.get("total").toString()) == 0){
				resultVo.setMessage("列表信息获取为空!");
			}
			resultVo.setData(map);
			resultVo.setSuccess(true);
		} catch (Exception e) {
			resultVo.setSuccess(false);
			resultVo.setMessage("列表信息获取失败！");
			log.error("列表信息获取失败！", e);
		}
		CommonUtil.PrintWriterResultVoWithJSON(response, resultVo);
	}
	
	/**
	 * 获取下拉列表数据（基础字典数据）
	 * 
	 * @param request
	 * @param response
	 * @param type
	 * @param id
	 * @param typeName
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/getCodeSelect")
	public void getCodeSelect(HttpServletRequest request,
			HttpServletResponse response, String type, String id,
			String typeName) {
		JSONArray array = new JSONArray();
		try {
			array = ddManagerService.getCodeSelect(type, typeName, id);
		} catch (Exception e) {
			log.error("列表信息获取失败！", e);
		}
		CommonUtil.PrintJSONSTR(response, array.toString());
	}

	/**
	 * 获取小区列表
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/getHousesList")
	public void getHousesList(HttpServletRequest request,
			HttpServletResponse response, String cityId) {
		ResultVo resultVo = new ResultVo();
		try {
			Map<String,Object> map = hrHouseInfoService.getCityHouseList(cityId);
			if(Integer.valueOf(map.get("total").toString())==0){
				resultVo.setMessage("列表信息为空");
			}
			resultVo.setSuccess(true);
			resultVo.setData(map);
		} catch (Exception e) {
			resultVo.setSuccess(false);
			resultVo.setMessage("小区列表获取失败！");
			log.error("小区列表获取失败！", e);
		}
		CommonUtil.PrintWriterResultVoWithJSON(response, resultVo);
	}

	/**
	 * 获取用心中心列表
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/getHouseUserList")
	public void getHouseUserList(HttpServletRequest request,
			HttpServletResponse response,String authenticationStatus, String currentPage, String pageSize) {
		ResultVo resultVo = new ResultVo();
		String weixinId = CommonUtil.getWeixinID(request);
		try {
			int total = (int)houseUserService.getMyHouseUserListCount(weixinId, authenticationStatus);
			PageVo<HouseUser> pageVo = new PageVo<HouseUser>(currentPage,total,pageSize);
			List<HouseUser> list = houseUserService.getMyHouseUserList(weixinId, authenticationStatus, 
					pageVo.getpageIndex(), pageVo.getpageSize());
			
			//图片地址转换
			for (HouseUser houseUser : list){
				List<FileVo> fileVoList = FileVo.getFileVoList(request, houseUser.getHrHouses().getUrl());
				houseUser.getHrHouses().setOther(fileVoList);
			}			
			
			pageVo.setData(list);
			resultVo.setSuccess(true);
			if(list!=null && list.size()>0){
				resultVo.setData(pageVo);
			}else{
				resultVo.setData(pageVo);
				resultVo.setMessage("获取用心中心列表为空!");
			}
		} catch (Exception e) {
			e.printStackTrace();
			resultVo.setSuccess(false);
			resultVo.setMessage("获取用心中心列表失败！");
		}
		List list = Arrays.asList("houseRepairs",
				"visitorCheckIns", "tenementCosts", "expresses","messageHouses","newsHouses","optimizedHouses");
		CommonUtil.PrintWriterResultWithJSON(response, resultVo, list);
	}

	/**
	 * 修改是否为当前住所
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/editIsDomicile")
	public void editIsDomicile(HttpServletRequest request,
			HttpServletResponse response, String userId) {
		ResultVo resultVo = new ResultVo();
		String weixinId = CommonUtil.getWeixinID(request);
		try {
			hrHouseInfoService.editIsDomicile(weixinId, userId);
			resultVo.setSuccess(true);
		} catch (Exception e) {
			e.printStackTrace();
			resultVo.setSuccess(false);
			resultVo.setMessage("修改是否为当前住所失败！");
		}
		CommonUtil.PrintWriterResultVoWithJSON(response, resultVo);
	}
	
	/**
	 * 获取物业地址列表
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/getHouseUserAddress")
	public void getHouseUserAddress(HttpServletRequest request,
			HttpServletResponse response,String codeId, String currentPage, String pageSize) {
		ResultVo resultVo = new ResultVo();
		String weixinId = CommonUtil.getWeixinID(request);
		try {
			int total = (int)houseUserService.getHouseUserListCount(weixinId, codeId);
			PageVo<HouseUser> pageVo = new PageVo<HouseUser>(currentPage,total,pageSize);

			List<Map<String, String>> list =  houseUserService.getHouseUserList(weixinId, codeId,
					pageVo.getpageIndex(), pageVo.getpageSize());
			
			PageVo<Map<String, String>> pageVoMap = new PageVo<Map<String, String>>(currentPage,total,pageSize);
			pageVoMap.setData(list);
			
			if(list!=null && list.size()>0){
				resultVo.setSuccess(true);
				resultVo.setData(pageVoMap);
			}else{
				resultVo.setSuccess(true);
				resultVo.setData(pageVoMap);
				resultVo.setMessage("获取物业地址列表为空!");
			}
		} catch (Exception e) {
			e.printStackTrace();
			resultVo.setSuccess(false);
			resultVo.setMessage("获取物业地址列表失败！");
		}
		CommonUtil.PrintWriterResultVoWithJSON(response, resultVo);
	}

	/**
	 * 获取物业地址列表
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/getUserAddress")
	public void getUserAddress(HttpServletRequest request,
			HttpServletResponse response,String authenticationStatus, String currentPage, String pageSize) {
		ResultVo resultVo = new ResultVo();
		String weixinId = CommonUtil.getWeixinID(request);
		try {
			int total = (int)houseUserService.getMyHouseUserListCount(weixinId, authenticationStatus);
			PageVo<HouseUser> pageVo = new PageVo<HouseUser>(currentPage,total,pageSize);

			List<Map<String, String>> list =  houseUserService.getMyTenementList(weixinId, authenticationStatus,
					pageVo.getpageIndex(), pageVo.getpageSize());
			
			PageVo<Map<String, String>> pageVoMap = new PageVo<Map<String, String>>(currentPage,total,pageSize);
			pageVoMap.setData(list);
			
			if(list!=null && list.size()>0){
				resultVo.setSuccess(true);
				resultVo.setData(pageVoMap);
			}else{
				resultVo.setSuccess(true);
				resultVo.setData(pageVoMap);
				resultVo.setMessage("获取物业地址列表为空!");
			}
		} catch (Exception e) {
			e.printStackTrace();
			resultVo.setSuccess(false);
			resultVo.setMessage("获取物业地址列表失败！");
		}
		CommonUtil.PrintWriterResultVoWithJSON(response, resultVo);
	}


	/**
	 * 业主信息添加修改
	 * 
	 * @param request
	 * @param response
	 * @param updateType
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/addOrUpdateHouseUser")
	public void addOrUpdateHouseUser(HttpServletRequest request,
			HttpServletResponse response, HouseUser houseUser,
			String updateType, String houseId ,String random) {
		System.out.println("用户基本信息添加："+houseUser.getName()+"|"+houseUser.getHouseId()+"|"+houseUser.getCusId()+"|"+houseUser.getResId()+"|"+houseUser.getCttId()+"|"+houseUser.getIDCardName()+"|"+houseUser.getIDCardNo()+"|"+houseUser.getWechatId()+"|"+houseUser.getTelephone()+"|"+houseUser.getAddress());
		ResultVo resultVo = new ResultVo();
		try {
			String phone = houseUser.getTelephone();
			String randomSMS = request.getSession().getAttribute(phone).toString();
			if (randomSMS.trim().length() > 0){
				if (randomSMS.equals(random) || randomSMS == random){
					houseUser.setHrHouses(new HrHouses(houseId));
					HrHouses houses = (HrHouses) this.findObject(HrHouses.class,houseId);
					houseUser.setAddress(houses.getProvince().getCodeDesc() + houses.getName() + houseUser.getResCode());
					
					houseUserService.saveOrUpdate(houseUser, updateType);
					
					resultVo.setSuccess(true);
					log.info("业主信息 " + updateType + "成功!");
				} else {
					resultVo.setSuccess(false);
					resultVo.setMessage("短信认证失败");
				}
			} else {
				resultVo.setSuccess(false);
				resultVo.setMessage("短信认证失败");
			}
		} catch (Exception e) {
			resultVo.setSuccess(false);
			resultVo.setMessage("业主信息 " + updateType + "失败");
			log.error("业主信息" + updateType + "失败!", e);
		}

		CommonUtil.PrintWriterResultVoWithJSON(response, resultVo);
	}
	
	/**
	 * 获取需要认证用户的手机号列表
	 * @param request
	 * @param response
	 * @param userName
	 * @param projectId
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/ownerVerifyPhones")
	public void ownerVerifyPhones(HttpServletRequest request,
			HttpServletResponse response, String userName,
			String projectId) {
		ResultVo resultVo = new ResultVo();
		System.out.println(userName);
		try{
			ConditionVo conditionVo = new ConditionVo();
			conditionVo.setP0("UserRev_GetOwnerInfor");
			conditionVo.setP1(userName);
			conditionVo.setP2(projectId);
			Map<String,Object> map = houseUserService.userOwnerVerify(conditionVo);
			if(Integer.valueOf(map.get("total").toString())==0){
				resultVo.setMessage("列表信息为空");
			}
			resultVo.setSuccess(true);
			resultVo.setData(map);
			
		}catch(SYHttpclientCallException e){
			resultVo.setSuccess(false);
			resultVo.setMessage(e.getMessage());
		}catch(Exception e){
			resultVo.setSuccess(false);
			resultVo.setMessage("获取手机号码列表失败");
		}
		CommonUtil.PrintWriterResultVoWithJSON(response, resultVo);
	}
	
	/**
	 * 生成手机验证码,发送短信到指定手机
	 * @param request
	 * @param response
	 * @param phone
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/sendSms")
	public void postValidateCode(HttpServletRequest request,
			HttpServletResponse response, String phone, String buildingName) {
		ResultVo resultVo = new ResultVo();
		try{
			//设置请求网易云信的header参数，详见http://dev.netease.im/docs?doc=server&#接口概述
			String url = VlidateDataTools.POST_URL;
			String nonce = VlidateDataTools.randomString(16);
			String curTime = String.valueOf((new Date()).getTime() / 1000L);
			
			String CheckSum  =  CheckSumBuilder.getCheckSum(VlidateDataTools.AppSecret, nonce, curTime);
			Map<String,String> headerParam = new HashMap<String,String>();
			headerParam.put("AppKey", VlidateDataTools.AppKey);
			headerParam.put("Nonce", nonce);
			headerParam.put("CurTime", curTime);
			headerParam.put("CheckSum", CheckSum);
			headerParam.put("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
			
			Random random = new Random();
			int randomSMS = random.nextInt(8999);
			randomSMS = randomSMS+1000;
			request.getSession().setAttribute(phone, randomSMS);
			
			Map<String,String> params = new HashMap<String,String>();
			params.put("templateid", VlidateDataTools.SmsTemplateid);
			params.put("mobiles", "[\""+phone+"\"]");
			params.put("params", "[\""+buildingName+"\",\""+randomSMS+"\"]");
			
			String content = HttpUtil.Post(url, headerParam, params);
			System.out.println(phone+"|"+randomSMS+"|"+content);
			resultVo.setMessage(content);
		}catch(SYHttpclientCallException e){
			resultVo.setSuccess(false);
			resultVo.setMessage(e.getMessage());
		}catch(Exception e){
			resultVo.setSuccess(false);
			resultVo.setMessage("发送短信失败");
		}
		CommonUtil.PrintWriterResultVoWithJSON(response, resultVo);
	}
}
